import { each, isArray } from 'lodash';
import { Modal } from 'antd';
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
export default class Excel {

    constructor(store) {
        this.workbook = window.GC.Spread.Sheets.findControl(document.getElementById(`edcWorkbookOfPage${store.pageid}`));
        this.store = store;
    }
    bind = (event, callback) => {
        this.workbook.bind(event, callback);
    }
    getSheets = () => {
        return this.workbook.sheets;
    }
    getSheetFromName = (sheetName) => {
        return this.workbook.getSheetFromName(sheetName);
    }
    getActiveSheet = () => {
        return this.workbook.getActiveSheet();
    }
    getDetailTable = (tableName) => {
        const [sheetName, dtName] = tableName.split('.');
        if (sheetName && dtName) {
            const sheet = this.workbook.getSheetFromName(sheetName);
            if (sheet) {
                return sheet.tables.findByName(dtName);
            }
        }
        return null;
    }
    getFieldValue = (fieldName = '') => {
        const [sheetName, fieldOrDetail, detailRow, detailField] = fieldName.split('.');
        if (sheetName) {
            const sheet = this.workbook.getSheetFromName(sheetName);
            if (sheet) {
                const ds = sheet.getDataSource();
                if (ds) {
                    return ds.getValue(fieldName);
                }
            }
        }
        return null;
    }
    setFieldValue = (fieldName, fieldValue) => {
        const [sheetName] = fieldName.split('.');
        if (sheetName) {
            const sheet = this.workbook.getSheetFromName(sheetName);
            if (sheet) {
                const ds = sheet.getDataSource();
                if (ds) {
                    this.workbook.suspendPaint();
                    ds.setValue(fieldName, fieldValue);
                    this.store.calcAll(true, sheetName);
                    this.workbook.resumePaint();
                }
            }
        }
    }

    /**
    * 字段名称转换为字段id
    */
    convertFieldNameToId = (fieldName) => {
        const [sheetName, fieldOrDetail, detailField] = fieldName.split('.');
        let cellType;
        if (detailField) {
            const detailMark = `${sheetName}.${fieldOrDetail}.0.${detailField}`;
            cellType = this.getFieldInfo(detailMark);
        } else {
            cellType = this.getFieldInfo(fieldName);
        }
        if (cellType && cellType.id) {
            return cellType.id
        }
    }

    /**
     * 改变单个字段显示属性(只读、编辑、必填)
     */
    changeFieldAttr = (fieldName, viewAttr) => {
        const [sheetName] = fieldName.split('.');
        if (sheetName) {
            const sheet = this.workbook.getSheetFromName(sheetName);
            if (sheet) {
                sheet.suspendPaint();
                const cellType = this.getFieldInfo(fieldName);
                const fieldIndex = excel.getFieldIndex(fieldName);
                const { row, col } = fieldIndex;
                if (cellType && cellType.viewAttr) {
                    cellType.viewAttr = viewAttr;
                }
                if (cellType.typeName == 'WeaSelectCellType' && viewAttr == 1) {
                    const json = cellType.toJSON();
                    const { items } = json;
                    sheet.getCell(row, col).cellType(new WeaSelectReadonlyCellType());
                    sheet.getCell(row, col).cellType().fromJSON(json);
                    sheet.getCell(row, col).cellType().typeName = 'WeaSelectReadonlyCellType';
                    sheet.getCell(row, col).cellType().items = items;
                } else if (cellType.typeName == 'WeaSelectReadonlyCellType' && viewAttr != 1) {
                    const json = cellType.toJSON();
                    const { items } = json;
                    sheet.getCell(row, col).cellType(new WeaSelectCellType());
                    sheet.getCell(row, col).cellType().fromJSON(json);
                    sheet.getCell(row, col).cellType().typeName = 'WeaSelectCellType';
                    sheet.getCell(row, col).cellType().items(items);
                }
                sheet.resumePaint();
            }
        }
    }

    /**
     * 添加明细及设置初始值
     */
    addDetailRow = (detailMark, initAddRowData) => {
        const [sheetName, detailIndex] = detailMark.split('.');
        if (sheetName) {
            const sheet = this.workbook.getSheetFromName(sheetName);
            if (sheet && detailIndex) {
                const tableName = detailIndex.replace('_', '');
                const table = this.getDetailTable(`${sheetName}.${tableName}`);
                const { row, colCount, rowCount, col } = table.dataRange();
                sheet.suspendPaint();
                const bindingPath = table.bindingPath();
                const records = this.getFieldValue(bindingPath);
                let newRecords = [];
                const index = rowCount - 1;
                if (records) {
                    if (records.length == 0) {
                        newRecords.push({ detail_index: 1 });
                    } else {
                        records.forEach((record, recordIndex) => {
                            if (recordIndex < index) {
                                newRecords.push(record);
                            } else if (recordIndex === index) {
                                newRecords.push(record);
                                newRecords.push({ ...initAddRowData, detail_index: recordIndex + 2 });
                            } else {
                                newRecords.push({ ...record, detail_index: recordIndex + 2 });
                            }
                        });
                    }
                }
                this.setFieldValue(bindingPath, newRecords);
                table.bindingPath(bindingPath);
                this.store.calcAll(true, sheetName);
                this.store.setUserinfo2newRow(table, row + rowCount, 1);
                this.store.setDetailTableRowHeight();
                sheet.resumePaint();
            }
        }
    }

    /**
     * 删除明细表指定行/全部行
     */
    delDetailRow = (detailMark, rowIndexMark) => {
        const [sheetName, detailIndex] = detailMark.split('.');
        if (sheetName) {
            const sheet = this.workbook.getSheetFromName(sheetName);
            if (sheet && detailIndex) {
                sheet.suspendPaint();
                const tableName = detailIndex.replace('_', '');
                const table = this.getDetailTable(`${sheetName}.${tableName}`);
                const { row, colCount, col } = table.dataRange();
                const bindingPath = table.bindingPath();
                let newRecords = [];
                const records = this.getFieldValue(bindingPath);
                if (rowIndexMark === "all") {
                    records.splice(0, records.length);
                } else {
                    const rowIndexs = rowIndexMark.split(',');
                    rowIndexs.sort((a, b) => { return b - a }).map(rowIndex => {
                        records.splice(rowIndex, 1);
                    });
                }
                records.forEach((record, recordIndex) => {
                    newRecords.push({ ...record, detail_index: recordIndex + 1 });
                });
                this.setFieldValue(bindingPath, newRecords);
                table.bindingPath(bindingPath);
                this.store.calcAll(true, sheetName);
                sheet.resumePaint();
            }
        }

    }

    /**
    * 获取明细已有行的数据库主键
    */
    getDetailRowKey = (detailMark) => {
        const record = this.getFieldValue(detailMark);
        if (record && record.id) {
            return record.id;
        } else {
            return '-1';
        }
    }

    /**
    * 获取字段的行列索引
    */
    getFieldIndex = (fieldName) => {
        const [sheetName, fieldOrDetail, detailRow, detailField] = fieldName.split('.');
        let fieldIndex = {};
        if (sheetName) {
            const sheet = this.workbook.getSheetFromName(sheetName);
            if (sheet && fieldOrDetail) {
                const tableName = fieldOrDetail.replace('_', '');
                const table = this.getDetailTable(`${sheetName}.${tableName}`);
                if (table) {
                    const bindingPath = table.bindingPath();
                    if (bindingPath) {
                        const { row, colCount, rowCount, col } = table.dataRange();
                        for (let i = 0; i < colCount; i++) {
                            const columnDataField = table.getColumnDataField(i);
                            if (columnDataField == detailField) {
                                if (detailRow)
                                    fieldIndex = { sheet: sheet, row: row + Number(detailRow), col: col + i };
                            }
                        }
                    }
                }
                if (!(detailRow && detailField)) {
                    const { data } = sheet.toJSON();
                    if (data) {
                        const { dataTable } = data;
                        if (dataTable) {
                            each(dataTable, (o, rowIndex) => {
                                each(o, (obj, colIndex) => {
                                    const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                                    if (bindingPath) {
                                        if (bindingPath == fieldName) {
                                            fieldIndex = { sheet: sheet, row: Number(rowIndex), col: Number(colIndex) };
                                        }
                                    }
                                });
                            });
                        }
                    }
                }
            }
        }
        return fieldIndex;
    }

    /**
    * 实时获取明细总行数
    */
    getDetailRowCount = (detailMark) => {
        const records = this.getFieldValue(detailMark);
        if (records) {
            return records.length;
        } else {
            return '-1';
        }
    }

    /**
     * 获取设计总行数
     */
    getRowCount = () => {

    }

    /**
    * 扩展浏览按钮取数接口参数值
    */
    appendBrowserDataUrlParam = (fieldMark, jsonParam = {}) => {
        const cellType = this.getFieldInfo(fieldMark);
        if (cellType) {
            let dataParams = cellType.dataParams;
            cellType.dataParams = {
                ...dataParams,
                ...jsonParam
            }
        }
    }

    /**
    * 获取浏览按钮的显示值
    */
    getBrowserShowName = (fieldMark, splitChar) => {
        const value = this.getFieldValue(fieldMark);
        if (value && isArray(value)) {
            return value.map(v => v.names || v.name).join(splitChar || ',');
        }
    }

    /**
    * 移除选择框字段选项
    */
    removeSelectOption = (fieldMark, optionKeys) => {
        const cellType = this.getFieldInfo(fieldMark);
        if (cellType) {
            const fieldIndex = this.getFieldIndex(fieldMark);
            const { sheet, row, col } = fieldIndex;
            const json = cellType.toJSON();
            const { items } = json;
            let newOptions = items;
            sheet.suspendPaint();
            if (optionKeys) {
                // let newOptions = cellType.items();
                const optionKeyArr = optionKeys.split(',');
                newOptions && optionKeyArr && optionKeyArr.length > 0 && optionKeyArr.map(key => {
                    newOptions = newOptions.filter(o => o.value !== key + '');
                })
            }
            if (cellType.typeName == 'WeaSelectCellType') {
                cellType.items(newOptions);
            } else if (cellType.typeName == 'WeaSelectReadonlyCellType') {
                cellType.items = newOptions;
            }
            sheet.getCell(row, col).value(null);
            sheet.resumePaint();

        }
    }

    /**
    * 控制选择框字段选项
    */
    controlSelectOption = (fieldMark, optionKeys) => {
        const cellType = this.getFieldInfo(fieldMark);
        const options = [];
        if (cellType) {
            const fieldIndex = this.getFieldIndex(fieldMark);
            const { sheet, row, col } = fieldIndex;
            sheet.suspendPaint();
            if (optionKeys) {
                // let newOptions = cellType.items();
                const json = cellType.toJSON();
                const { items: newOptions } = json;
                const optionKeyArr = optionKeys.split(',');
                newOptions && optionKeyArr && optionKeyArr.length > 0 && optionKeyArr.map(key => {
                    const temp = newOptions.filter(o => o.value == key + '')[0];
                    if (temp) {
                        options.push(temp);
                    }
                })
            }
            if (cellType.typeName == 'WeaSelectCellType') {
                cellType.items(options);
            } else if (cellType.typeName == 'WeaSelectReadonlyCellType') {
                cellType.items = options;
            }
            sheet.getCell(row, col).value(null);
            sheet.resumePaint();
        }
    }

    /**
    * 获取选择框字段的显示值
    */
    getSelectShowName = (fieldMark) => {
        const cellType = this.getFieldInfo(fieldMark);
        if (cellType) {
            let options = [];
            if (cellType.typeName == 'WeaSelectCellType') {
                options = cellType.items();
            } else if (cellType.typeName == 'WeaSelectReadonlyCellType') {
                options = cellType.items;
            }
            // let options = cellType.items();
            const value = this.getFieldValue(fieldMark);
            const option = options.filter(o => o.value == value + '')[0];
            if (option) {
                return option.text;
            }
        }
    }

    /**
    * 获取字段信息
    */
    getFieldInfo = (fieldMark) => {
        const [sheetName, fieldOrDetail, detailRow, detailField] = fieldMark.split('.');
        if (sheetName) {
            const sheet = this.workbook.getSheetFromName(sheetName);
            if (sheet) {
                const fieldIndex = excel.getFieldIndex(fieldMark);
                const { row, col } = fieldIndex;
                if (row != null && typeof row != 'undefined' && col != null && typeof col != 'undefined') {
                    const cellType = sheet.getCell(row, col).cellType();
                    return cellType;
                }
            }
        }
    }

    /**
     * 获取字段当前的只读/必填属性
     */
    getFieldCurViewAttr = (fieldMark) => {
        const cellType = this.getFieldInfo(fieldMark);
        if (cellType && cellType.viewAttr) {
            return cellType.viewAttr
        }
    }

    /**
     * 控制日期浏览按钮的可选日期范围
     */
    controlDateRange = (fieldMark, start, end) => {
        try {
            let startDate = '';
            let endDate = '';
            const reg = /^(-?\d+)(\.\d+)?$/;
            if (typeof start !== "undefined") {
                startDate = start.toString();
                if (reg.test(startDate))
                    startDate = new Date(new Date().getTime() + start * 24 * 60 * 60 * 1000).toLocaleDateString();
            }
            if (typeof end !== "undefined") {
                endDate = end.toString();
                if (reg.test(endDate))
                    endDate = new Date(new Date().getTime() + end * 24 * 60 * 60 * 1000).toLocaleDateString();
            }
            startDate = startDate.replace(/-/g, '/');
            endDate = endDate.replace(/-/g, '/');
            const cellType = this.getFieldInfo(fieldMark);
            if (cellType) {
                cellType.startDate = startDate;
                cellType.endDate = endDate;
            }
        } catch (e) {

        }
    }

    hideInsertSpanRow = (bindingPath) => {
        if(this.store.hideInsertSpanRow){
            this.store.hideInsertSpanRow.push(bindingPath);
        }else{
            this.store.hideInsertSpanRow=[bindingPath];
        }
        excel.store.reEnterCell();
    }
    hideInsertTopRow = (bindingPath) => {
        if(this.store.hideInsertTopRow){
            this.store.hideInsertTopRow.push(bindingPath);
        }else{
            this.store.hideInsertTopRow=[bindingPath];
        }
        excel.store.reEnterCell();
    }
    hideInsertBottomRow = (bindingPath) => {
        if(this.store.hideInsertBottomRow){
            this.store.hideInsertBottomRow.push(bindingPath);
        }else{
            this.store.hideInsertBottomRow=[bindingPath];
        }
        excel.store.reEnterCell();
    }
    hideDeleteRow = (bindingPath) => {
        if(this.store.hideDeleteRow){
            this.store.hideDeleteRow.push(bindingPath);
        }else{
            this.store.hideDeleteRow=[bindingPath];
        }
        excel.store.reEnterCell();
    }
    hideEdcTaskViewBtn = (btnName) => {
        if(!this.store.parent) return;
        const task = this.store.parent().task;
        switch (btnName) {
            case 'submit':this.store.parent().task={...task,canSubmit:false};break;
            case 'undo':this.store.parent().task={...task,hasUndoBtn:false};break;
            case 'save':this.store.parent().task={...task,hasSaveBtn:false};break;
            case 'distribute':this.store.parent().task={...task,hasDistributeBtn:false};break;
            case 'export':this.store.parent().task={...task,hasExportBtn:false};break;
            case 'import':this.store.parent().task={...task,hasImportBtn:false};break;
            case 'cover':this.store.parent().task={...task,hasCoverBtn:false};break;
            case 'reject':this.store.parent().task={...task,hasRejectBtn:false};break;
            case 'batchReject':this.store.parent().task={...task,hasBatchRejectBtn:false};break;
            case 'collect':this.store.parent().task={...task,hasCollectBtn:false};break;
        }
    }
    triggleEdcTaskViewBtn = (btnName) => {
        if(!this.store.parent) return;
        const taskViewStore = this.store.parent();
        const params = taskViewStore.params;
        switch (btnName) {
            case 'submit':if(taskViewStore.canSubmit && taskViewStore.task.canSubmit) taskViewStore.submit();break;
            case 'undo':if (taskViewStore.canUndo && taskViewStore.task.hasUndoBtn) taskViewStore.undo(params);break;
            case 'save':if(taskViewStore.canSubmit && taskViewStore.task.hasSaveBtn) taskViewStore.save();break;
            case 'distribute':
                    if(taskViewStore.canSubmit && taskViewStore.task.hasDistributeBtn){
                        if (taskViewStore.hasSheetIds) { 
                            taskViewStore.setIssueVisible(true)
                        }else{
                            if (taskViewStore.distributeBrowser) {
                                taskViewStore.distributeBrowser.openModal();
                            }
                        }
                    }
                    break;
            case 'export':if(taskViewStore.tabs.length === 3 && taskViewStore.task.hasExportBtn) taskViewStore.exportExcel();break;
            case 'import':if(taskViewStore.canSubmit && taskViewStore.task.hasImportBtn) taskViewStore.setVisible(true);break;
            case 'cover':
                    if(taskViewStore.canSubmit && taskViewStore.hasChild && taskViewStore.task.hasCoverBtn){
                        Modal.confirm({
                            title: getLabel('510797','覆盖'),
                            content: <span>
                                {getLabel('510798','你已保存过数据，若获取最新数据，')}
                                <br/>
                                <span style={{color:'#f5222d'}}>{getLabel(504079, '其对应的数据也会被清除，并无法恢复')}</span>。
                                <br />
                                {getLabel('510799','你确定要覆盖吗？')}
                            </span>,
                            onOk: () => {
                                taskViewStore.resetCollect(params);
                            }});
                    }
                    break;
            //case 'reject':taskViewStore.reject();break;
            //case 'batchReject':taskViewStore.batchReject();break;
            case 'collect':if(taskViewStore.reportType && !taskViewStore.canSubmit && taskViewStore.task.hasCollectBtn) taskViewStore.forcedCollect(params);break;
        }
    }
}